package org.kur.modularization.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.compress.CompressUtil;
import cn.hutool.extra.compress.extractor.Extractor;

import java.io.File;
import java.nio.charset.Charset;
import java.util.Arrays;

public class Utils {
    /**
     * 解压
     *
     * @param jarFile JAR 文件
     * @return {@link File 解压后的目录}
     *///解压
    public static File decompression(File jarFile) {
        String fileName = getFileName(jarFile.getName());
        Extractor extractor = CompressUtil.createExtractor(Charset.defaultCharset(), FileUtil.file(jarFile));
        File file = new File(jarFile.getParentFile(), fileName);
        extractor.extract(file);
        return file;
    }

    /**
     * 获取文件名
     *
     * @param jarName JAR 名称
     * @return {@link String 返回Jar包的文件名}
     */
    public static String getFileName(String jarName) {
        String[] parts = jarName.split("\\.");
        String newFileName = String.join(".", Arrays.copyOfRange(parts, 0, parts.length - 1));
        System.out.println(newFileName);
        return newFileName;
    }


    public static String getOutPutFileName(String fileName) {
        String start = "writing to";
        int startIndex = fileName.indexOf(start);
        int endIndex = fileName.indexOf("module-info.java");
        if (startIndex != -1 && endIndex != -1) {
            return fileName.substring(startIndex + start.length() + 3, endIndex - 1);
        } else {
            return "解析失败";
        }
    }
}
